<template>
	<view class="pointCenter">
     <!-- 兑换详情 -->
     <view class="top-box">
       <view class="img-x">
         <image :src="giftInfo.img" class='imgge'></image >
       </view>
       <view class="text1">
         <p class="title">{{giftInfo.title}}</p>
         <p class="p2">{{pointsAmount}}积分</p>
         <p>兑换时间：{{filterChecked.redeemGiftParseDate(giftInfo.startAt)}} - {{filterChecked.redeemGiftParseDate(giftInfo.endAt)}}</p>
       </view>
     </view>
     <view class="bottom-box">
       <h2>兑换说明</h2>
	   <p class="p-one">
		   <u-parse :content="giftInfo.description"></u-parse>
	   </p>
     </view>
     <button type="default" class="button" style="background-color: #444;width: 32%;color:#FFFFFF;font-size: 26rpx;line-height: 60rpx;height: 60rpx;" @click="redeemGift(giftInfo)">兑换</button>

    <!--兑换礼品失败遮盖弹层-->
    <view class="bg" v-if="redeemGiftError || redeemGiftSuccess || clickRedeemGift"></view>

	<view class="success-pop" v-if="redeemGiftError">
	  <i class="iconfont icon-cuowu1" @click="closeBox"></i>
	  <view class="goPoints">{{redeemTip}}</view>
	  <view class="goPoints" v-if="redeemTipPs">{{redeemTipPs}}</view>
	</view>

	<view class="success-pop" v-if="redeemGiftSuccess">
	  <i class="iconfont icon-cuowu1" @click="closeBox"></i>
	  <view class="goPoints">{{redeemTip}}</view>
	  <view class="goPoints">立即填写礼品&nbsp;&nbsp;<text @click="setShippingAddress" class="address-underline">寄送地址</text></view>
	</view>

	<!-- 确认兑换提示 -->
	<view class="success-pop" v-if="clickRedeemGift">
	  <i class="iconfont icon-cuowu1" @click="closeBox"></i>
	  <view class="goPoints">{{redeemTip}}</view>
	  <view class="goPoints"><text @click="continueRedeem" class="underline">兑换</text></view>
	</view>
    </view>
</template>

<script module="filterChecked" lang="wxs" src="../../../utils/filter.wxs"></script>
<script>
  import api from '@/api/api';
  import {CUSTOMER_INFO, USER_INFO} from '../../../utils/constant';
  import uParse from "../components/feng-parse/parse.vue"
	export default {
    components: {
    		  uParse: uParse,
    		},
		data() {
			return {
				giftInfo:Object,
				redeemGiftSuccess:false,
				redeemGiftError:false,
				typeId:'',
				pointsAmount:0,
				redeemTip:'',
				redeemTipPs:'',
				clickRedeemGift:false,
				redeemGiftInfo:Object,
        nowPages: '',

			}
		},

    onLoad(option) {
      let that = this;
	  that.typeId = option.type_id;
	  that.getGiftInfo(option.type_id);
    let pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.nowPages = currPage.route;
    },
    onShow() {
       let that = this;
       getApp().cl_tracker.track('mini_program_view', {
         path: this.nowPages,
         pageName: '积分兑礼',
       })
     },
	methods: {
		setShippingAddress(){
			let that = this;
			uni.navigateTo({
			  url:'/pages/address/address?type=redeemGift&giftOrderId='+that.giftOrderId
			})
		},
		closeBox(){
		  let that = this;
		  that.redeemGiftSuccess = false;
		  that.redeemGiftError = false;
		  that.clickRedeemGift = false;
		},
		getGiftInfo:async function(typeId){
			let that = this;
			let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
			const giftInfo = await api.giftInfo({
			  header: {jwt: customerInfo.jwt}
			},typeId);
			if (giftInfo.code === 1000) {
			    that.giftInfo = giftInfo.data.params;
				that.pointsAmount = giftInfo.data.pointsAmount;
			}
		},

		redeemGift(giftInfo){
			let that = this;
			that.redeemGiftInfo = giftInfo;
			that.clickRedeemGift = true;
			that.redeemTip = '请再次确认使用积分兑换礼品'
		},

		continueRedeem:async function(){
			let that = this;
			that.clickRedeemGift = false;
			let giftInfo = that.redeemGiftInfo;
			let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
			const parmas = {
			  typeId: that.typeId,
			}
			const redeemRs = await api.redeemGift({
			  header: {
				jwt: customerInfo.jwt},
				query: parmas,
				method: 'POST',
			});
			if (redeemRs.code === 1000) {
				that.redeemGiftSuccess = true;
				that.giftOrderId = redeemRs.data.entityId;
				that.filterErrorMsg(redeemRs.msg);
			}else{
				that.redeemGiftError = true;
				let msg = redeemRs.msg;
				if(redeemRs.code === -1008){
					let startDate = giftInfo.startAt.split(" ");
					let endDate = giftInfo.endAt.split(" ");

					let startDateTimestamp = Date.parse(startDate[0]);
					let toDateTimestamp = Date.parse(endDate[0]);
					var timestamp = (new Date()).getTime();
					// 日期满足,时间不满足
					if(timestamp > startDateTimestamp && timestamp < toDateTimestamp){
						let start = giftInfo.startTime;
						if(start !== '' && start !== undefined && start !== null){
							let hour =  start.split(":");
							that.redeemTip = hour[0]+"点开启兑换";
							that.redeemTipPs = '敬请期待';
						}else{
							that.filterErrorMsg(msg);
						}
					}else{
						that.filterErrorMsg(msg);
					}

				}else if(redeemRs.code === -1007){
					that.filterErrorMsg(msg);
					that.redeemTipPs = '现登记生日即可获享积分';
				}else{
					that.filterErrorMsg(msg);
				}
			}
		},
		filterErrorMsg(sysError){
			let that = this;
			that.redeemTipPs = '';
			if(sysError.search('，') !== -1 && sysError.search('。') !== -1){
				sysError.replace('。','，');
				let tips = [];
				tips = sysError.split('，');
				that.redeemTip = tips[0];
				for(var i =1; i<tips.length; i++){
					that.redeemTipPs += tips[i].substr(0,tips[i].length)+'，';
				}
				that.redeemTipPs = that.redeemTipPs.substr(0,that.redeemTipPs.length -2);
			}else if(sysError.search('。') ){
				that.redeemTip = sysError.substr(0,sysError.length -1);
			}
		},

       couponList: async function(){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const json = await api.redeemListCoupon({
          header: {'jwt': customerInfo.jwt},
        });

        if (json.code === 1000) {
            that.couponItems = json.data;
        }
      },


      getPointsTransaction: async function(currentPage){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const parmas = {
          page: currentPage,
          size: that.pageSize,
          sort: 'CreatedAt',
          sort_dir: 'DESC'
        }

        const json = await api.pointsTransaction({
          header: {'jwt': customerInfo.jwt},
          query: parmas
        });
        if (json.code === 1000) {
          let data = json.data.data;
          that.pageTotal = data.totalPages;
          that.pointsList = [...that.pointsList, ...data.content];
        }
      },


      /**
       * 积分总览
       * */
      pointsInfo: async function(){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const json = await api.pointsInfo({
          header: {'jwt': customerInfo.jwt},
        });
        if (json.code === 1000) {
          that.pointsOverview = json.data;
        }
      },

      /**
       * 兑换券
       * */
      redeemCoupon:async function(typeId){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const json = await api.redeemCoupon({
          header: {'jwt': customerInfo.jwt},
          method: 'POST',
          query: {
            typeId: typeId,
          }
        });
        if (json.code === 1000) {
          that.redeemCouponSuccess = true;
          that.pointsInfo();
        }else{
          that.redeemCouponError = true;
          if(json.code === -1006){
            that.redeemErrorMsg = '你的会员等级不符，暂不可兑';
          }else if(json.code === -1007){
            that.redeemErrorMsg = '积分余额不足，暂不可兑';
          }else if(json.code === -1008){
            that.redeemErrorMsg = '活动尚未开启，敬请期待';
          }
        }
      },



      //加载更多
      onReachBottom() {
        let that = this;
        //判断总页数是否大于翻页数
        if ((that.pageTotal) > that.currentPage) {
          //防止重复加载
          if (that.preventRepeatReuqest) {
            return true;
          }
          that.preventRepeatReuqest = true;
          that.currentPage++;
          that.getPointsTransaction(that.currentPage);
          that.preventRepeatReuqest = false;
        }
      },

      onPullDownRefresh() {
        wx.showNavigationBarLoading();    //在当前页面显示导航条加载动画
        this.pointsList = [];
        this.currentPage = 1;
        this.getPointsTransaction(this.currentPage);
        setTimeout(function () {
          wx.hideNavigationBarLoading();    //在当前页面隐藏导航条加载动画
          wx.stopPullDownRefresh();    //停止下拉动作
        }, 2000)
      },


		}
	}
</script>

<style lang="less">
.pointsBox{

  .total{display:flex;justify-content:space-between;}
  .total label{display: block;font-size:56rpx;line-height: 60rpx;}
  .tip view{font-size:22rpx;}
  .btn{
    background-color: #444;color:#fff;
    width:170rpx;height: 56rpx;
    line-height: 56rpx;margin-top: 32rpx;
  }
}
.tabTitle{display: flex;border-top:2rpx solid #ccc;}
.tabTitle label{width:50%;text-align: center;padding:16rpx 0;background-color:#eee;color:#999;border-bottom:2rpx solid #ccc;}
.tabTitle label:first-child{border-right:2rpx solid #ccc;}
.tabTitle label.act{color:#333;background-color: #fff;border-bottom:none;}

.tabMain{margin-bottom:100rpx;}
.tabMain .item{padding:24rpx 40rpx;border-bottom:2rpx solid #ccc;}
.tabMain .item .h5{display: flex;justify-content: space-between;margin-bottom:14rpx;font-size:30rpx;}
.tabMain .item .time{color:#999;}
.header {
  height: 350rpx;
  width: 750rpx;
  display: flex;
  align-items: center;
  background-image: url('https://efc-public-assets-1252208446.cos.ap-shanghai.myqcloud.com/images/crm/2020011519589.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.header_content {
  width: 100%;
  text-align: center;
}
.nickName {
  font-size: 30rpx;
  color: #fff;
  text-align: center;
  display: block;
  margin: 20rpx auto 0;
}
.member {
  text-decoration: underline;
  color: #fff;
  display: inline-block;
  padding: 0 40rpx;
}
.topUserInfo .member{
  padding:0;
  text-decoration: none;
  text-align: left;
}
.pointsInfo{
  text-align: left;
}
.avatarUrl {
  width: 118rpx;
  height: 118rpx;
  display: block;
  border-radius: 1000px;
  margin-right:50rpx;
}
.point-num{
  background-repeat: no-repeat;
  background-size: 5%;
  background-position: 45% center;
  padding-left: 60rpx;
  background-image: url('https://efs-cloud-miniprogram-store-1252208446.cos.ap-shanghai.myqcloud.com/images/cos-miniprogram/point-icon.png');
}
.pointsBox .total {
  display: flex;
  justify-content: space-between;
  padding-top: 30rpx;
  line-height: 46rpx;
}
.pointsBox .total label {
  display: block;
  font-size: 56rpx;
  line-height: 60rpx;
}
.pointsBox .btn {
  background-color: #444;
  color: #fff;
  width: 170rpx;
  height: 56rpx;
  line-height: 56rpx;
  margin-top: 38rpx;
}
.pointsBox .tip {
  margin-top: 36rpx;
}
.points-Block{
  background: #f0f0f0;
  width: 750rpx;
  padding-bottom: 50rpx;
}
.points-Block .text{
padding: 40rpx 30rpx;
font-size: 34rpx;
  }
.exchange-content{
  padding: 0 75rpx;
  background-image: url('https://efs-cloud-miniprogram-store-1252208446.cos.ap-shanghai.myqcloud.com/images/cos-miniprogram/coupon.png');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  height: 230rpx;
  position: relative;
  margin-bottom:10rpx;
}
  .exchange-num{
    color: #444444;
    position: absolute;
    top: 9%;
    margin: 0;
    right: 10%;
    background-size: 22%;
    background-position: 30% center;
    width: 170rpx;
    text-align: center;
    /*background-image: url('https://efs-cloud-miniprogram-store-1252208446.cos.ap-shanghai.myqcloud.com/images/cos-miniprogram/point-b.png');*/
  }
  .tip .second{
    float: right;
  }
.success-pop{
  border: 1px solid #eee;
  position: absolute;
  width: 400rpx;
  text-align: center;
  padding: 30px;
  top: 30%;
  background: #fff;
  z-index: 2;
  left: 50%;
  transform: translate(-50%, 0);

}
.success-pop .iconfont{
  position: absolute;
  padding: 15rpx 15rpx 30rpx 30px;
  cursor: pointer;
  right: 0;
  top: 0;
}
.goPoints{
  line-height: 25px;
}
.bg{
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  width: 100vw;
  height: 100vh;
  left: 0;
  top: 0;
  z-index: 1;
}
  .points-gain{
    position: relative;
  }
.points-gain  .map{
  width: 22%;
  height: 34%;
  bottom: 13%;
  right: 39%;
  position: absolute;
  z-index: 1;
}
  .underline{
    text-decoration: underline;
  }

  .address-underline{
	text-decoration: underline;
	font-size: 35rpx;
	font-weight: bold;
  }
  .points-image{position: relative;}
  .points-image-link{position: absolute;left:0;top:0;width:92.2%;height:100%;display: flex;padding: 0 30rpx;}
  .points-image-link view{width:33.33%;}
.avatarUrlImg {
  width: 100rpx;
  height: 100rpx;
  border-radius: 1000px;
}
.userName{color:#fff;text-align: left;}
.member-Level{color:#fff;margin: 6rpx 0;}
.topUserInfo{display: flex;padding:0 0 30rpx 120rpx;}




</style>
<style>
  .pointCenter{height: 100%;}
  .imgge{width: 580rpx;height: 580rpx;}
  .img-x{display:flex;justify-content: center; margin-top: 30rpx;}
  .text1{margin: 30rpx ;text-align: center;}
  /* .text1 h2{margin: 40rpx 0;font-size: 30rpx;} */
  .top-box{background-color: #f0f0f0;padding-top: 30rpx;padding-bottom: 35rpx;}
  .text1 .p2{margin-top: 22rpx;}
  .bottom-box{text-align: left;margin: 70rpx 60rpx 60rpx 60rpx;}
  .bottom-box h2{text-align: center;font-size: 30rpx;}
  .bottom-box .p-one{margin-top: 40rpx;}
  .bottom-box p{line-height: 42rpx;font-size: 20rpx;}
  .title{
	  font-size: 30rpx;
  }
</style>
